package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.view.DatePickerDialog;

import org.json.JSONException;
import org.json.JSONObject;

import static com.gongpingjialoan.R.id.phone;

/**
 * 预约新车
 */
public class SubscribeNewCarActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout permute_layout;
    private TextView submit, code_btn;
    private EditText nameEt, phoneEt, codeEt;
    private CheckBox permute_check;
    private TextView cityT;

    private TimeCount time = null;
    private NetDataJson mNetDataJson; //短信
    private NetDataJson submi_net;

    private TextView modelT, car_licenseT;//车辆型号,上牌时间
    private EditText distanceEt;//行驶里程,车辆卖价
    private ImageView carImg;
    private TextView carName;

    private String mBrandSlug, mBrandName, mModelSlug, mModelName, mModelDetailSlug, mModelDetailName, mModelThumbnail, mMile, mCarPrice;
    private String mYear, mMonth;
    private String maxyear = null, minyear = null;
    private DatePickerDialog dateDialog;

    private final int REQUEST_CITY_FRAGMENT = 1;
    public static final int REQUEST_BRAND = 2;
    private String str_city;

    private String carid = "";
    private String shareJo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe_new_car);

        initView();
    }

    private void initView() {
        setTitle("预约新车");

        carid = getIntent().getStringExtra("carid");
        carid = "1";
        JSONObject detail;

        permute_layout = (LinearLayout) findViewById(R.id.permute_layout);
        submit = (TextView) findViewById(R.id.submit_subscribe);
        code_btn = (TextView) findViewById(R.id.code_btn);
        nameEt = (EditText) findViewById(R.id.name);
        phoneEt = (EditText) findViewById(phone);
        codeEt = (EditText) findViewById(R.id.code);
        permute_check = (CheckBox) findViewById(R.id.permute_check);
        modelT = (TextView) findViewById(R.id.model);
        car_licenseT = (TextView) findViewById(R.id.car_license);
        distanceEt = (EditText) findViewById(R.id.distance);
        cityT = (TextView) findViewById(R.id.city);
        carImg = (ImageView) findViewById(R.id.carImg);
        carName = (TextView) findViewById(R.id.carName);

        nameEt.addTextChangedListener(new MyTextWatcher());
        phoneEt.addTextChangedListener(new MyTextWatcher());
        codeEt.addTextChangedListener(new MyTextWatcher());
        modelT.addTextChangedListener(new MyTextWatcher());
        car_licenseT.addTextChangedListener(new MyTextWatcher());
        distanceEt.addTextChangedListener(new MyTextWatcher());
        cityT.addTextChangedListener(new MyTextWatcher());

        submit.setOnClickListener(this);
        code_btn.setOnClickListener(this);
        modelT.setOnClickListener(this);
        car_licenseT.setOnClickListener(this);
        cityT.setOnClickListener(this);

        time = new TimeCount(60000, 1000);

        permute_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    permute_layout.setVisibility(View.VISIBLE);
                } else {
                    permute_layout.setVisibility(View.GONE);
                }
                isReady();
            }
        });

        try {
            detail = new JSONObject(getIntent().getStringExtra("detail"));
            ImageLoad.LoadImage(carImg, detail.getString("image_url"), R.drawable.car_loading, R.drawable.car_loading, this);
            carName.setText(detail.getString("model") + " " + detail.getString("model_detail"));
            String city = GPJApplication.getInstance().getCityData().mCurrentCity;
            cityT.setText(TextUtils.isEmpty(city) ? "" : city);
            if (GPJApplication.getInstance().isLogin()){
                UserManager mUserManager = new UserManager(this);
                mUserManager = mUserManager.LoadUserInfo();
                phoneEt.setText(mUserManager.getPhone());
            }else {

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.model:
//                if (!DealerApplication.getInstance().getReady())
//                {
//                    Toast.makeText(SubscribeNewCarActivity.this,"数据未加载成功,请检查网络是否连接!",Toast.LENGTH_SHORT).show();
//                    return;
//                }
                intent = new Intent();
                intent.setClass(SubscribeNewCarActivity.this, CategoryActivity.class);
                intent.putExtra("needModelDetailFragment", true);
                startActivityForResult(intent, REQUEST_BRAND);
                break;
            case R.id.car_license:
                if (TextUtils.isEmpty(modelT.getText().toString())) {
                    Toast.makeText(SubscribeNewCarActivity.this, "请选择车辆型号!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (null != dateDialog && maxyear != null) {
                    dateDialog.show();
                } else {
                    Toast.makeText(SubscribeNewCarActivity.this, "上牌时间数据加载中!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.city:
                intent = new Intent();
                intent.setClass(SubscribeNewCarActivity.this, CityActivity.class);
//                if (!TextUtils.isEmpty(mModelSlug)) {
//                    intent.putExtra("show_county", true);
//                }
                startActivityForResult(intent, REQUEST_CITY_FRAGMENT);

                break;
            case R.id.submit_subscribe:
                submit();
                break;
            case R.id.code_btn:
                getVergifyCode();
                break;
            default:
                break;
        }
    }

    private void submit() {
        if (submi_net == null) {
            submi_net = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    Toast.makeText(SubscribeNewCarActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    JSONObject jo = null;
                    try {
                        jo = new JSONObject(json);
                        if (jo != null) {
                            shareJo = jo.getJSONObject("share").toString();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Intent it = new Intent(SubscribeNewCarActivity.this, SubscribeSucceedActivity.class);
                    it.putExtra("share", shareJo);
                    startActivity(it);
                    finish();
                }
            }, 1);
        }

        String phone = phoneEt.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(SubscribeNewCarActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (phone.length() < 11) {
            Toast.makeText(SubscribeNewCarActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        String name = nameEt.getText().toString();
        String code = codeEt.getText().toString();
        String detail = "";
        if (permute_check.isChecked()) {
            JSONObject jo = new JSONObject();
            try {
                jo.put("brand", mBrandName);
                jo.put("model", mModelName);
                jo.put("model_detail", mModelDetailName);
                jo.put("brand_slug", mBrandSlug);
                jo.put("model_slug", mModelSlug);
                jo.put("detail_slug", mModelDetailSlug);
                jo.put("mile", mMile);
                jo.put("year", mYear);
                jo.put("month", mMonth);
                jo.put("city", cityT.getText().toString());
                detail = jo.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String url = NetDataJson.NEWCAR_SERVER_DOMAIN + "/api/v2/tesla/campaign_cars/" + carid + "/orders/";
        submi_net.setUrl(url);
        submi_net.setUseOtherDomain(true);
        submi_net.addParam("name", name);
        submi_net.addParam("phone", phone);
        submi_net.addParam("is_displaced", permute_check.isChecked());
        submi_net.addParam("captcha", code);
//        submi_net.addParam("detail", detail);
        submi_net.request("post");
    }

    private void getVergifyCode() {
        if (mNetDataJson == null) {
            mNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    time.cancel();
                    code_btn.setEnabled(true);
                    code_btn.setText("获取验证码");
                    Toast.makeText(SubscribeNewCarActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    time.start();
                    Toast.makeText(SubscribeNewCarActivity.this, "验证码获取成功,请注意查收!", Toast.LENGTH_SHORT).show();
                }
            }, 1);
        }

        String phone = phoneEt.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(SubscribeNewCarActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (phone.length() < 11) {
            Toast.makeText(SubscribeNewCarActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = NetDataJson.NEWCAR_SERVER_DOMAIN + "/api/v2/tesla/captcha/";
        mNetDataJson.setUrl(url);
        mNetDataJson.setUseOtherDomain(true);
        mNetDataJson.addParam("phone", phone);
        mNetDataJson.request("post");
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            code_btn.setText("重新发送");
            code_btn.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            code_btn.setEnabled(false);
            code_btn.setText(millisUntilFinished / 1000 + "秒");

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (submi_net != null) {
            submi_net.cancelTask();
            submi_net = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 车型选择回调
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    onBrandSelceted(bundle);
                    break;
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    str_city = b.getString("city", "");
                    if (!TextUtils.isEmpty(str_city)) {
                        cityT.setText(str_city);
                    } else {
                        cityT.setText("-");
                    }
                    break;
                default:
                    break;
            }
        }

    }

    // 选择完车型后,调用这辆
    public void onBrandSelceted(Bundle bundle) {
        maxyear = null;
        minyear = null;
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");
        mModelThumbnail = bundle.getString("modelThumbnail");

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            modelT.setText(mModelName);
        } else {
            modelT.setText(mModelName + " " + mModelDetailName);
        }

        // delete the date data if it is not null
        car_licenseT.setText("");

        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(SubscribeNewCarActivity.this);
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);

        dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    car_licenseT.setText(year + "年");
                } else {
                    car_licenseT.setText(year + "年" + month + "月");
                }
            }
        });

        // // 如果是评估我的车,上牌年份的日期从返回的数据bundle中取
        // if (radioG.getCheckedRadioButtonId() == R.id.radio_left)
        // {
        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(SubscribeNewCarActivity.this, "没有可选的上牌时间!", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            isReady();
        }
    }

    //监听所有数据填满 才可以点击提交
    public void isReady() {
        submit.setBackgroundResource(R.color.text_grey_dark);
        submit.setEnabled(false);
        if (TextUtils.isEmpty(nameEt.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(phoneEt.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(codeEt.getText().toString())) {
            return;
        }
        if (permute_check.isChecked()) {
            if (TextUtils.isEmpty(modelT.getText().toString())) {
                return;
            }
            if (TextUtils.isEmpty(car_licenseT.getText().toString())) {
                return;
            }
            if (TextUtils.isEmpty(distanceEt.getText().toString())) {
                return;
            }
            if (TextUtils.isEmpty(cityT.getText().toString())) {
                return;
            }
        }
        submit.setBackgroundResource(R.color.blue_3fbbff);
        submit.setEnabled(true);
    }
}
